package com.fuint.module.schedule;

import cn.hutool.core.collection.CollUtil;
import com.fuint.common.enums.PayStatusEnum;
import com.fuint.common.service.CommissionLogService;
import com.fuint.common.service.OrderService;
import com.fuint.common.util.DateUtil;
import com.fuint.common.util.LogUtils;
import com.fuint.framework.exception.BusinessCheckException;
import com.fuint.repository.model.MtOrder;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 分销提成计算定时任务
 */
@EnableScheduling
@Component("CommissionJob")
@RequiredArgsConstructor
public class CommissionJob {
    /**
     * 订单服务接口
     */
    private final OrderService orderService;
    /**
     * 分佣记录服务接口
     */
    private final CommissionLogService commissionLogService;
    /**
     * 系统环境变量
     */
    private final Environment environment;
    /**
     * 一次最多处理订单数量
     **/
    private final static int MAX_ROWS = 10;
    /**
     * 订单完成后n天可产生佣金
     */
    private final static int OVER_DAY = 7;

    @Scheduled(cron = "${commission.job.time}")
    @Transactional(rollbackFor = Exception.class)
    public void dealOrder() throws BusinessCheckException {
        String theSwitch = environment.getProperty("commission.job.switch");
        if (theSwitch != null && theSwitch.equals("1")) {
            LogUtils.info("CommissionJobStart!!!");
            Map<String, Object> param = new HashMap<>();
            param.put("PAY_STATUS", PayStatusEnum.SUCCESS.getKey());

            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -OVER_DAY);
            Date dateTime = calendar.getTime();
            String endTime = DateUtil.formatDate(dateTime, "yyyy-MM-dd HH:mm:ss");

            List<MtOrder> dataList = orderService.getTobeCommissionOrderList(endTime);
            if (CollUtil.isNotEmpty(dataList)) {
                int dealNum = 0;
                for (MtOrder mtOrder : dataList) {
                    if (Objects.isNull(mtOrder)) {
                        continue;
                    }
                    // 计算订单佣金
                    if (dealNum <= MAX_ROWS) {
                        commissionLogService.calculateCommission(mtOrder.getId());
                        dealNum++;
                    }
                }
            }
            LogUtils.info("CommissionJobEnd!!!");
        }
    }
}
